package com.example.controller;

import com.example.dao.EmployeeDAO;
import com.example.dao.SalaryDAO;
import com.example.model.Employee;
import com.example.model.Salary;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

import java.util.List;

@WebServlet(name = "SalaryServlet", value = {
        "/salaries", "/addSalary", "/editSalary", "/updateSalary", "/deleteSalary"
})
public class SalaryServlet extends HttpServlet {
    private SalaryDAO salaryDAO;
    private EmployeeDAO employeeDAO;
    private static final int RECORDS_PER_PAGE = 5;

    @Override
    public void init() {
        salaryDAO = new SalaryDAO();
        employeeDAO = new EmployeeDAO();
    }

    private boolean isAdmin(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        return session != null && "admin".equals(session.getAttribute("role"));
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (!isAdmin(request)) {
            response.sendRedirect("login.jsp");
            return;
        }
        String action = request.getServletPath();

        if ("/addSalary".equals(action)) {
            addSalary(request, response);
        } else if ("/updateSalary".equals(action)) {
            updateSalary(request, response);
        } else if ("/deleteSalary".equals(action)) {
            deleteSalary(request, response);
        } else {
            response.sendRedirect("salaries");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        if (!isAdmin(request)) {
            response.sendRedirect("login.jsp");
            return;
        }
        String action = request.getServletPath();

        if ("/salaries".equals(action)) {
            listSalaries(request, response);
        } else if ("/addSalary".equals(action)) {
            showAddForm(request, response);
        } else if ("/editSalary".equals(action)) {
            showEditForm(request, response);
        } else if ("/deleteSalary".equals(action)) {
            deleteSalary(request, response);
        } else {
            response.sendRedirect("salaries");
        }
    }

    private void listSalaries(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取当前页码，默认为第一页
            int page = 1;
            String pageParam = request.getParameter("page");
            if (pageParam != null && !pageParam.isEmpty()) {
                page = Integer.parseInt(pageParam);
            }

            // 获取工资记录总数
            int totalSalaries = salaryDAO.getTotalSalaries();
            int totalPages = (int) Math.ceil((double) totalSalaries / RECORDS_PER_PAGE);

            // 设置请求属性
            request.setAttribute("salaries", salaryDAO.getAllSalaries(page, RECORDS_PER_PAGE));
            request.setAttribute("currentPage", page);
            request.setAttribute("totalPages", totalPages);
            request.setAttribute("totalSalaries", totalSalaries);

            // 转发到列表页面
            RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/listSalaries.jsp");
            dispatcher.forward(request, response);
        } catch (Exception e) {
            throw new ServletException("Error listing salaries", e);
        }
    }

    private void showAddForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            List<Employee> employees = employeeDAO.getAllEmployees();
            request.setAttribute("employees", employees);
            RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/addSalary.jsp");
            dispatcher.forward(request, response);
        } catch (Exception e) {
            throw new ServletException("Error showing add form", e);
        }
    }

    private void addSalary(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Salary salary = new Salary();
        salary.setEmpId(Integer.parseInt(request.getParameter("empId")));
        salary.setBaseSalary(Double.parseDouble(request.getParameter("baseSalary")));
        salary.setBonus(Double.parseDouble(request.getParameter("bonus")));
        salary.setDeduction(Double.parseDouble(request.getParameter("deduction")));


        try {
            salaryDAO.addSalary(salary);
            // 添加成功后重定向到工资列表
            response.sendRedirect("salaries");
        } catch (Exception e) {
            throw new ServletException("Error adding salary", e);
        }
    }
    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            int salaryId = Integer.parseInt(request.getParameter("id"));
            Salary salary = salaryDAO.getSalaryById(salaryId);
            List<Employee> employees = employeeDAO.getAllEmployees();

            if (salary != null) {
                request.setAttribute("salary", salary);
                request.setAttribute("employees", employees);
                RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/editSalary.jsp");
                dispatcher.forward(request, response);
            } else {
                response.sendRedirect("salaries");
            }
        } catch (Exception e) {
            throw new ServletException("Error showing edit form", e);
        }
    }

    private void updateSalary(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Salary salary = new Salary();
        salary.setSalaryId(Integer.parseInt(request.getParameter("id")));
        salary.setEmpId(Integer.parseInt(request.getParameter("empId")));
        salary.setBaseSalary(Double.parseDouble(request.getParameter("baseSalary")));
        salary.setBonus(Double.parseDouble(request.getParameter("bonus")));
        salary.setDeduction(Double.parseDouble(request.getParameter("deduction")));


        try {
            salaryDAO.updateSalary(salary);
            response.sendRedirect("salaries");
        } catch (Exception e) {
            throw new ServletException("Error updating salary", e);
        }
    }

    private void deleteSalary(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int salaryId = Integer.parseInt(request.getParameter("id"));
        try {
            salaryDAO.deleteSalary(salaryId);
            response.sendRedirect("salaries");
        } catch (Exception e) {
            throw new ServletException("Error deleting salary", e);
        }
    }
}
